package com.ycsj.goldmedalnewconcept.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.adapter.BabyHomeworkAdapter;
import com.ycsj.goldmedalnewconcept.bean.HomeWorkInfo;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.pickerview.view.TimePickerView;
import com.ycsj.goldmedalnewconcept.utils.GsonUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.view.PullToRefreshLayout;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 宝贝作业--家长端
 * <p>
 * Created by Administrator on 2018/1/2 0002.
 */

@SuppressLint("NewApi")
public class BabyHomeWorkActivity extends Activity implements
		View.OnClickListener, OnRefreshListener {
	// 正常加载
	public static final int NORMAL = 0X110;

	// 下拉刷新
	public static final int PULLTOREFRESH = 0X120;
	
	// 加载更多
	public static final int LOADMORE = 0X130;

	// 返回
	private LinearLayout llBack;

	// 右边的日历
	private RelativeLayout rlCander;

	// 加载
	private LinearLayout llLoading;

	// 空数据
	private LinearLayout llEmpty;

	// 显示月份的TextView
	private TextView tv_rili;

	// 刷新控件
	private PullToRefreshLayout ptrl;

	// 列表控件
	private ListView lv;

	// TimePickerView时间选择控件
	private TimePickerView pvTime;

	// 需要上传的年月
	private String yearmonth;

//	// 班级Id
//	private String classId;

	// 数据集合
	private List<HomeWorkInfo.ListBean> oldDatas;

	// 适配器对象
	private BabyHomeworkAdapter adapter;

	// 分页
	private int pager = 0;

	private String account;

	
	private View footerView;
	
	private View loading;
	
	private TextView loadTextView;
	private TextView tv_empty;
	
	private boolean isLoading = false;
	
	private RotateAnimation loadingAnimation;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_baby_home_wor);
		// 设置状态栏
		setBar();

//		// 获取传递过来的classId
//		initIntent();

		// 初始化控件
		initView();

		// 设置监听
		initListener();

		// 初始化ListView
		initLv();

		// 网络请求的方法
		http(NORMAL);
	}

//	/**
//	 * 获取传递过来的班级Id
//	 */
//	private void initIntent() {
//		classId = getIntent().getStringExtra("class_id");
//		Log.i("test", "获取到的classId是:" + classId);
//	}

	/**
	 * 初始化控件
	 */
	private void initView() {
		tv_rili = (TextView) findViewById(R.id.tv_rili);
		llBack = (LinearLayout) findViewById(R.id.ll_back);
		llLoading = (LinearLayout) findViewById(R.id.ll_loading);
		llEmpty = (LinearLayout) findViewById(R.id.ll_empty);
		rlCander = (RelativeLayout) findViewById(R.id.rl_cander);
		ptrl = (PullToRefreshLayout) findViewById(R.id.refresh_view);
		lv = (ListView) findViewById(R.id.lv);

		
		footerView = this.getLayoutInflater().inflate(R.layout.load_more_jpstar, null);
		loading = footerView.findViewById(R.id.loading_icon);
		loadTextView = (TextView) footerView.findViewById(R.id.loadmore_tv);
		tv_empty = (TextView) footerView.findViewById(R.id.tv_empty);
		lv.addFooterView(footerView, null, false);
		
		loadingAnimation = (RotateAnimation) AnimationUtils.loadAnimation(this,
				R.anim.rotating);
		// 添加匀速转动动画
		LinearInterpolator lir = new LinearInterpolator();
		loadingAnimation.setInterpolator(lir);
		
		
		// 初次进入的时候让标题栏的时间显示为当前的月份
		// 获取年份
		int year = Calendar.getInstance().get(Calendar.YEAR);
		// 获取月份
		int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
		if (month < 10) {
			yearmonth = year + "-0" + month;
		} else {
			yearmonth = year + "-" + month;
		}

		// 初始化第一次进入时请求的年月
//		tv_rili.setText((Calendar.getInstance().get(Calendar.MONTH) + 1) + "");
		
		if (month < 10) {
			tv_rili.setText("0" + month);
		} else {
			tv_rili.setText(month);
		}
		
		
	}

	/**
	 * 设置监听方法
	 */
	private void initListener() {
		llBack.setOnClickListener(this);
		rlCander.setOnClickListener(this);
		ptrl.setOnRefreshListener(this);
		footerView.setOnClickListener(this);
	}

	/**
	 * 初始化ListView的方法
	 */
	private void initLv() {
		oldDatas = new ArrayList<>();
		adapter = new BabyHomeworkAdapter(this, this, oldDatas,
				R.layout.item_lv_baby_homework);
	}

	/**
	 * 网络请求的方法
	 */
	private void http(final int method) {
		if (method == PULLTOREFRESH || method == NORMAL) {
			pager = 0;
		} else {
			pager++;
		}

		account = SPUtil.getString(this, "account", "");
		
		OkHttpClient mOkHttpClient = new OkHttpClient();
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "4");
		builder.add("c", account);
		builder.add("page", pager + "");
		builder.add("yearmonth", yearmonth);
//		builder.add("school", "");
//		builder.add("userclass",classId);
		builder.add("role", 1 + "");
//		builder.add("status", "");
		Request request = new Request.Builder()
//				.url("http://m.moregolden.com/ycsj_platform/ManageMsg")
				.url(Constant.SERVER_URL+"ManageMsg")
				.post(builder.build()).build();

		mOkHttpClient.newCall(request).enqueue(new Callback() {
			@Override
			public void onFailure(Request request, IOException e) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// 请求失败,主线程更新UI操作
						if (llLoading != null) {
							llLoading.setVisibility(View.GONE);
						}
						Toast.makeText(BabyHomeWorkActivity.this, "网络错误",
								Toast.LENGTH_SHORT).show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				try {
					// 请求成功
					// 获取服务器返回的json数据
					String json = arg0.body().string();
					if (!TextUtils.isEmpty(json)) {
						HomeWorkInfo info = GsonUtil.jsonToBean(json,
								HomeWorkInfo.class);
						// 获取列表数据
						final List<HomeWorkInfo.ListBean> beanList = info
								.getList();
						if (null != beanList && beanList.size() != 0) {
							// 证明有列表数据,更新主界面
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									if (method == NORMAL) {
										// 正常请求
										if (llLoading != null) {
											llLoading.setVisibility(View.GONE);
										}
										if (llEmpty != null) {
											llEmpty.setVisibility(View.GONE);
										}
										if (ptrl != null) {
											ptrl.setVisibility(View.VISIBLE);
										}
										oldDatas.addAll(beanList);
										lv.setAdapter(adapter);
									} else if(method == PULLTOREFRESH){
										// 下拉刷新
										oldDatas.clear();
										oldDatas.addAll(beanList);
										ptrl.refreshFinish(PullToRefreshLayout.REFRESH_SUCCEED);
										adapter.notifyDataSetChanged();
										
										
										if (null != llLoading
												&& llLoading.getVisibility() != View.GONE) {
											llLoading.setVisibility(View.GONE);
										}
										loadTextView.setText("加载更多");
										isLoading = false;
									}else{
										if (null != llLoading
												&& llLoading.getVisibility() != View.GONE) {
											llLoading.setVisibility(View.GONE);
										}
										loading.setVisibility(loading.GONE);
										loading.clearAnimation();
										if (beanList.size() < 10) {
											loadTextView.setText("已经是最后一条了");
											loadTextView.setClickable(false);
											isLoading = true;
										} else {
											loadTextView.setText("加载更多");
											isLoading = false;
										}
										
										oldDatas.addAll(beanList);
//										ptrl.refreshFinish(PullToRefreshLayout.REFRESH_SUCCEED);
										adapter.notifyDataSetChanged();
									}
								}
							});
						} else {
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									// 证明没有数据,显示空视图,隐藏加载框
									if (method == NORMAL) {
										// 正常加载
										if (llLoading != null) {
											llLoading.setVisibility(View.GONE);
										}
										if (llEmpty != null) {
											llEmpty.setVisibility(View.VISIBLE);
										}
										if (ptrl != null) {
											ptrl.setVisibility(View.GONE);
										}
										lv.setAdapter(adapter);
									} else if(method == PULLTOREFRESH){
										// 下拉刷新
										ptrl.refreshFinish(PullToRefreshLayout.REFRESH_FAIL);
									}else if(method == LOADMORE){
										
										if (null != llLoading
												&& llLoading.getVisibility() != View.GONE) {
											llLoading.setVisibility(View.GONE);
										}
										
										loading.setVisibility(loading.GONE);
										loading.clearAnimation();
										loadTextView.setText("没有更多的作业了");
										loadTextView.setClickable(false);
										isLoading = true;
//										page = 0;
										
									}
								}
							});
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					Toast.makeText(BabyHomeWorkActivity.this, "数据异常",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
	}

	/**
	 * 页面控件点击事件
	 *
	 * @param v
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ll_back:
			finish();
			break;
		case R.id.rl_cander:
			// 点击日历控件选择日期
			showTimePickUp();
			break;
		case R.id.loadmore_layout:
			if (!isLoading) {
				loading.setVisibility(View.VISIBLE);
				loading.startAnimation(loadingAnimation);
				loadTextView.setText("正在加载...");
				isLoading = true;
//				page++;
//				initData();
				
				// 网络请求的方法
				http(LOADMORE);
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 弹出选择时间的PopUpWinodw
	 */
	@SuppressLint("SimpleDateFormat")
	private void showTimePickUp() {

		pvTime = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH);

		pvTime.setTime(new Date());

		pvTime.setCyclic(false);

		pvTime.setCancelable(true);

		pvTime.show();
		// 时间选择后回调
		pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

			@Override
			public void onTimeSelect(Date date) {

				String newYearmonth = getTime(date);

				// 用"-切割"
				String[] datas = newYearmonth.split("-");

				// 分别取出年月
				String year = datas[0];
				String month = datas[1];

				if ("12".equals(month)) {
					// 如果显示的是2016-12月 ,则上传的时间需要时2017-01
					yearmonth = String.valueOf((Integer.valueOf(year) + 1))
							+ "-01";
				} else {
					// 判断month是否以0开头
					if (month.startsWith("0")) {
						// 以0开头,取出第二个字符转化为int 然后+1处理
						int res = Integer.valueOf(month.substring(1)) + 1;

						Log.i("test", "转换后的res的月份值是" + res);
						if (res < 10) {
							yearmonth = year + "-0" + res;
						} else {
							yearmonth = year + "-" + res;
						}

					} else {
						// 不以0开头,10和11
						int res = Integer.valueOf(month) + 1;
						yearmonth = year + "-" + res;
					}
				}

				Log.i("test", "获取到的时间是:" + yearmonth);

				// 重新设置标题栏显示月份的TextView
				tv_rili.setText(yearmonth.split("-")[1]);

				Log.i("test", "选中的年月是:" + yearmonth);

				// 重新请求服务器刷新页面数据,根绝服务器需要的上传的字段进行处理
				http(NORMAL);
			}

		});

	}

	/**
	 * 将Date时间转化为年月的方法
	 * 
	 * @param date
	 * @return
	 */
	public String getTime(Date date) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
		return format.format(date);
	}

	/**
	 * 下拉刷新
	 */
	@Override
	public void onRefresh() {
		http(PULLTOREFRESH);
	}

	/**
	 * 设置沉浸状态栏的方法,需要在setContentView()之后调用
	 */
	@SuppressLint("InlinedApi")
	private void setBar() {
		// 兼容5.0+，状态栏设置透明
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			Window window = getWindow();
			window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			window.getDecorView().setSystemUiVisibility(
					View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
							| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
			window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
			window.setStatusBarColor(Color.TRANSPARENT);
		} else
		// 为了沉浸式状态栏 4.4以上才有
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		}
	}

}
